package com.fare.taluo.application.impl.system.auth;

import java.util.ArrayList;
import java.util.List;

import org.openkoala.auth.application.RoleApplication;
import org.openkoala.auth.application.UserApplication;
import org.openkoala.auth.application.vo.RoleVO;
import org.openkoala.auth.application.vo.UserVO;
import org.openkoala.koala.auth.ss3adapter.SecurityMD5;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dayatang.domain.InstanceFactory;
import com.fare.taluo.application.impl.MyMD5Util;
import com.fare.taluo.application.plane.channel.SourceApplication;
import com.fare.taluo.application.system.auth.UserInfoApplication;
import com.fare.taluo.auth.domain.UserInfoEntity;
import com.fare.taluo.auth.security.ContextLoginUser;
import com.fare.taluo.auth.security.LogonUserCertificate;
import com.fare.taluo.base.ddd.application.BaseApplicationImpl;
import com.fare.taluo.vo.auth.RegisterVo;
import com.fare.taluo.vo.auth.UserInfoVO;
import com.fare.taluo.vo.core.SourceEntityVO;

@Service("userInfoApplication")
@Scope
public class UserInfoApplictionImpl extends BaseApplicationImpl implements
		UserInfoApplication {

	@Override
	public UserInfoVO getUserInfoByLogonid(String logonId) {
		String hql = "from UserInfoEntity u where u.loginId=?";
		UserInfoEntity entity = super.queryChannel().querySingleResult(hql,
				new Object[] { logonId });
		return this.domain2VO(entity);
	}

	@Override
	public UserInfoVO getUserInfoByLocalid(Long localId) {
		String hql = "from UserInfoEntity u where u.accoutId=?";
		UserInfoEntity entity = super.queryChannel().querySingleResult(hql,
				new Object[] { localId });
		return this.domain2VO(entity);
	}

	private UserInfoVO domain2VO(UserInfoEntity entity) {
		UserInfoVO vo = new UserInfoVO();

		vo.setUserId(entity.getId());
		vo.setAccoutId(entity.getAccoutId());
		vo.setSourceId(entity.getSourceId());
		vo.setCompany(entity.getSourceName());
		vo.setHbaseKey(entity.getSourceKey());
		vo.setCreateTime(entity.getCreateTime());
		vo.setEmail(entity.getEmail());
		vo.setLoginId(entity.getLoginId());
		vo.setMobile(entity.getMobile());
		vo.setUserName(entity.getName());
		vo.setPriority(entity.getPriority());
		vo.setQq(entity.getQq());
		vo.setRemark(entity.getRemark());
		vo.setSex(entity.getSex());
		vo.setTelephone(entity.getTelephone());
		return vo;
	}

	// 获取当前用户Info
	@Override
	public UserInfoVO getCurrentUser() {
		LogonUserCertificate user = ContextLoginUser.getLoginUser();
		if (null == user)
			return null;
		UserInfoVO userVo = new UserInfoVO();
		userVo.setUserName(user.getUserName());
		userVo.setLoginId(user.getLoginId());
		UserInfoVO vo = this.getUserInfoByLocalid(user.getLocalUserId());
		userVo.setUserId(user.getLocalUserId());
		userVo.setUserName(vo.getLoginId());
		userVo.setAccoutId(user.getUserId());
		userVo.setEmail(vo.getEmail());
		userVo.setTelephone(vo.getTelephone());
		userVo.setMobile(vo.getMobile());
		userVo.setPhone(vo.getMobile() == null ? vo.getMobile() : vo
				.getMobile());
		userVo.setQq(vo.getQq());
		userVo.setSourceId(user.getSourceId());
		userVo.setCompany(vo.getCompany());
		userVo.setHbaseKey(vo.getHbaseKey());
		userVo.setGroup(user.getRoleName());
		userVo.setSex(vo.getSex());
		userVo.setPriority(vo.getPriority());
		userVo.setHbaseKey(vo.getHbaseKey());
		userVo.setCompany(vo.getCompany());
		userVo.setGroupId(user.getRoleId());
		return userVo;
	}

	/**
	 * 用户密码修改
	 */
	@Override
	public boolean updatePassWord(Long userIds, String Password)
			throws Exception {
		org.openkoala.auth.application.vo.UserVO userVO = new org.openkoala.auth.application.vo.UserVO();
		LogonUserCertificate user = ContextLoginUser.getLoginUser();
		// UserInfoVO VO=this.getUserInfoByLogonid(userIds+"");
		userVO.setCreateOwner(user.getLoginId());
		userVO.setUserPassword(Password);// 新密码
		userVO.setName(user.getLoginId());

		UserVO vo = InstanceFactory.getInstance(UserApplication.class).getUser(
				userIds);
		boolean flag = InstanceFactory.getInstance(UserApplication.class)
				.updatePassword(userVO, vo.getUserPassword());

		return flag;

	}

	/**
	 * @see UserServiceImpl#checkInputPassword(long,String)
	 * */
	@Override
	public boolean checkInputPassword(Long userId, String password) {
		try {
			UserVO user = InstanceFactory.getInstance(UserApplication.class)
					.getUser(userId);
			if (null == user)
				return false;
			return MyMD5Util.validPassword(password, user.getUserPassword());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 更新一个用户
	 */
	@Transactional
	@Override
	public void updateUser(UserInfoVO entity) throws Exception {
		UserInfoEntity vo = new UserInfoEntity();
		vo.setId(entity.getUserId());
		vo.setAccoutId(entity.getAccoutId());
		vo.setSourceId(entity.getSourceId());
		vo.setSourceName(entity.getCompany());
		vo.setCreateTime(entity.getCreateTime());
		vo.setEmail(entity.getEmail());
		vo.setLoginId(entity.getLoginId());
		vo.setMobile(entity.getMobile());
		vo.setName(entity.getUserName());
		vo.setPriority(entity.getPriority());
		vo.setQq(entity.getQq());
		vo.setRemark(entity.getRemark());
		vo.setSex(entity.getSex());
		vo.setTelephone(entity.getTelephone());
		vo.setSourceKey(entity.getHbaseKey());
		vo.saveOrUpate(vo);

	}

	/**
	 * 检查用户所输入信息是否已注册
	 */
	@Override
	public boolean queryIsExist(Long ids, String email, String userName)
			throws Exception {
		UserInfoEntity qu = new UserInfoEntity();
		Boolean falg = false;
		falg = qu.queryIsExist(ids, email, userName);
		return falg;
	}

	@Override
	public void save(RegisterVo vo) {
		UserApplication userApplication = InstanceFactory
				.getInstance(UserApplication.class);
		RoleApplication roleApplication = InstanceFactory
				.getInstance(RoleApplication.class);
		SourceApplication sourceApplication = InstanceFactory
				.getInstance(SourceApplication.class);
		UserVO userVO = new UserVO();
		userVO.setName(vo.getUserName());
		userVO.setUserAccount(vo.getUserName());
		userVO.setUserPassword(vo.getPassword());
		userVO.setUserPassword(SecurityMD5.encode(userVO.getUserPassword(),
				userVO.getUserAccount()));
		userVO.setValid(true);
		userVO.setSerialNumber("0");
		userVO.setSortOrder(0);
		userVO.setVersion(0);
		// 保存koala登陆帐号
		userVO = userApplication.saveUser(userVO);
		List<RoleVO> listRole = new ArrayList<RoleVO>();
		// 保存koala下角色
		RoleVO role = roleApplication.getRole(vo.getGroup());
		listRole.add(role);
		userApplication.assignRole(userVO, listRole);
		// 保存魔方上用户信息
		SourceEntityVO source = sourceApplication.findByHbaseKey(vo
				.getSourceId());
		UserInfoEntity userInfo = new UserInfoEntity();
		userInfo.setAccoutId(userVO.getId());
		userInfo.setEmail(vo.getEmail());
		userInfo.setLoginId(vo.getUserName());
		userInfo.setMobile(vo.getPhone());
		userInfo.setName(vo.getUserName());
		userInfo.setQq(vo.getQq());
		userInfo.setTelephone(vo.getPhone());
		userInfo.setSourceId(source.getId());
		userInfo.setSourceKey(source.getHbaseKey());
		userInfo.setSourceName(source.getName());
		userInfo.save();
	}

	@Transactional
	@Override
	public boolean deleteUser(Long userId) {
		String hql = "from UserInfoEntity u where u.accoutId=?";
		UserInfoEntity entity = super.queryChannel().querySingleResult(hql,
				new Object[] { userId });
		entity.delete();
		return true;
	}

}
